package com.ruoyi.controller;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.center.domain.NoticeCenter;
import com.ruoyi.center.service.INoticeCenterService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.param.impl.GetUserDataByIdRequestParam;
import com.param.impl.IdParam;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.recharge.domain.Recharge;
import com.ruoyi.recharge.service.IRechargeService;
import com.ruoyi.user.service.IMgUserService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.pay.type.domain.PayType;
import com.ruoyi.pay.type.service.IPayTypeService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 充值记录 Controller
 * 
 * @author 王强
 * @date 2023-12-22
 */
@RestController
@RequestMapping("/system/recharge")
public class RechargeController extends BaseController
{
    @Autowired
    private IRechargeService rechargeService;
    
    private IMgUserService userService;
    
    IPayTypeService payTypeService;

    @Autowired
    private INoticeCenterService centerService;

    
    @Autowired
    public void setPayTypeService(IPayTypeService payTypeService) {
		this.payTypeService = payTypeService;
	}


	/**
     * 查询充值记录 列表
     */
    @PreAuthorize("@ss.hasPermi('finance:desposit:single')")
    @GetMapping("/listByUserId")
    public TableDataInfo listByUserId( @Validated GetUserDataByIdRequestParam id)
    {
        startPage();
        List<Recharge> list = rechargeService.selectList(id);
        return getDataTable(list);
    }
    

    /**
     * 查询充值记录 列表
     */
    @PreAuthorize("@ss.hasPermi('system:recharge:list')")
    @GetMapping("/list")
    public TableDataInfo list(Recharge recharge)
    {
        startPage();
        List<Recharge> list = rechargeService.selectList(recharge);
        return getDataTable(list);
    }
    

    /**
     * 导出充值记录 列表
     */
    @PreAuthorize("@ss.hasPermi('system:recharge:export')")
    @Log(title = "充值记录 ", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Recharge recharge)
    {
        List<Recharge> list = rechargeService.selectList(recharge);
        ExcelUtil<Recharge> util = new ExcelUtil<Recharge>(Recharge.class);
        util.exportExcel(response, list, "充值记录 数据");
    }

    /**
     * 获取充值记录 详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:recharge:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return success(rechargeService.selectById(id));
    }

    /**
     * 新增充值记录 
     */
    @PreAuthorize("@ss.hasPermi('system:recharge:add')")
    @Log(title = "充值记录 ", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Recharge recharge)
    {
        return toAjax(rechargeService.insert(recharge));
    }

    /**
     * 变更已支付
     */
    @PreAuthorize("@ss.hasPermi('finance:recharge:changePayment')")
    @Log(title = "充值记录 ", businessType = BusinessType.UPDATE)
    @PutMapping("changePayment")
    @Transactional(propagation = Propagation.REQUIRED)
    public AjaxResult changePayment(@RequestBody Recharge recharge)
    {
    	
    	String payStatus = recharge.getPayStatus();
    	
		Integer payId = recharge.getPayId();
		
		Integer id = recharge.getId();
		
		Recharge selectById = rechargeService.selectById(id);
    	
    	if (null == selectById) {
    		return AjaxResult.error("找不到记录");
    	}
    	
    	if (selectById.getPayStatus().equals("1")) {
    		return AjaxResult.error("已支付完成");
    	}

    	
    	if (null == payStatus ||  "0".equals(payStatus)) {
    		
    		if (0 != payId.compareTo(selectById.getPayId())) {
    			// 更新 支付方式
    			if (!updatePayType(recharge, payId)) {
    	    		 return AjaxResult.error("找不到支付方式");
    	    	}
    			
    			rechargeService.update(recharge);
    		}
    		
    		
    		return success();
    	}
    	
    	
		if (null == id || 0 == id) {
            return AjaxResult.error("id不能为空");
        }
    	
		
		if (null == payId || 0 == payId) {
            return AjaxResult.error("支付Id不能为空");
        }
		
    
    	if (!updatePayType(recharge, payId)) {
    		 return AjaxResult.error("找不到支付方式");
    	}
    	
        int update = rechargeService.updatePayment(recharge);
        
        // 更新用户金额
        int updateAcademicCurrency = userService.updateAcademicCurrency(recharge.getAccount(), selectById.getUserId().intValue());

        NoticeCenter center = new NoticeCenter();

        center.setUserId(selectById.getUserId().intValue());

        // 您的预存金额【¥XXX】单号YC202xxxxxxxxxXX已提交，请耐心等待平台处理
        BigDecimal amount = recharge.getAccount();
        center.setNoticeContent("您的预存金额【￥"+ amount +"】 单号"+selectById.getOrderSn()+" 预存成功，快去看看吧~");

        center.setPlatform(0);

        center.setNoticeType(4);

        center.setTitle("预存金额通知");

        center.setTypeId(selectById.getId());

        centerService.insert(center);
		return toAjax(updateAcademicCurrency);
    }


	protected boolean updatePayType(Recharge recharge, Integer payId) {
		PayType payDataById = payTypeService.selectById(payId);
    	
    	if (null == payDataById) {
            return false;
        }
    	
    	recharge.setPyName(payDataById.getTypeName());
    	
    	return true;
	}
    
    /**
     * 修改充值记录 
     */
    @PreAuthorize("@ss.hasPermi('system:recharge:edit')")
    @Log(title = "充值记录 ", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Recharge recharge)
    {
        int update = rechargeService.update(recharge);
		return toAjax(update);
    }

    /**
     * 删除充值记录 
     */
    @PreAuthorize("@ss.hasPermi('system:recharge:remove')")
    @Log(title = "充值记录 ", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(rechargeService.deleteByIds(ids));
    }

	public IMgUserService getUserService() {
		return userService;
	}

	@Resource
	public void setUserService(IMgUserService userService) {
		this.userService = userService;
	}
}
